fromEvent
及map
來計算一下頁面scroll的狀態
,不囉嗦,立馬練習!import {fromEvent} from 'rxjs'
fromEvent(document, 'scroll').subscribe(console.log); // 順利的話,scroll event都會印出囉!
import {fromEvent} from 'rxjs'
fromEvent(document, 'scroll')
.pipe(
// 使用map來解析scrollEvent的資訊,計算出scroll百分比
map((event: Event) => {
const { scrollTop, scrollHeight, clientHeight } =
event.target.scrollingElement; //<--解析1: 從event.target.scrollingElement拆解出scrollTop, scrollHeight, clientHeight
const percent = (scrollTop / (scrollHeight - clientHeight)) * 100; // 解析2: 計算百分比
return percent.toFixed(2); // 解析3: 四捨五入一下
})
)
.subscribe(console.log);
scrollingElement
,所以透過event.target.scrollingElement
就可以取得囉!scrollBar的百分比
,故需要三個參數scrollTop, scrollHeight, clientHeight
,這三個參數的定義,可以參考下圖或Shubo的這篇。 <!-- 記得將此img的部分移除或comment -->
...
<!-- 新增一個scrollbar在此 -->
<div
class="progress-bar"
style="
position: fixed;
height: 5px;
width: 0%; //<-- 可以先設定 >0%來看看是不是有順利繪出
top: 0;
background-color: skyBlue;
"
></div>
fromEvent(document, 'scroll')
.pipe(
map((event: Event) => {
const { scrollTop, scrollHeight, clientHeight } =
event.target.scrollingElement;
const percent = (scrollTop / (scrollHeight - clientHeight)) * 100;
return percent.toFixed(2);
})
)
.subscribe(
// console.log
(percent) =>
(document.querySelector('.progress-bar').style.width = `${percent}%`) // 修改 progress-bar element中,width的百分比
);